package com.lin.reggie.service.Impl;

import com.lin.reggie.entity.ShoppingCart;
import com.lin.reggie.mapper.ShoppingCartMapper;
import com.lin.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    private HttpSession session;


    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        //调用查询购物车数据 接口方法 创建对象
        ShoppingCart dbShoppingCart = shoppingCartMapper.findByShoppingCart(shoppingCart);
        //判断数据是否为空
        if (dbShoppingCart!=null){
            //如果购物车有，那就number字段  +1
            dbShoppingCart.setNumber(dbShoppingCart.getNumber()+1);
            shoppingCartMapper.updateNumber(dbShoppingCart.getId(),dbShoppingCart.getNumber());
        }else {
            //将购物车数据复制给接口数据
            dbShoppingCart=shoppingCart;
            //设置创建时间
            dbShoppingCart.setCreateTime(LocalDateTime.now());
            //设置number1
            dbShoppingCart.setNumber(1);
            //调用接口插入数据
            shoppingCartMapper.save(dbShoppingCart);
        }
        //返回数据
        return dbShoppingCart;
    }

    //查看购物车
    @Override
    public List<ShoppingCart> findCartByUserId(Long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findCartByUserId(userId);
        return shoppingCartList;
    }
    @Override
    public void deleteShopp(Long userId) {
        shoppingCartMapper.clean(userId);
    }

    @Override
    public ShoppingCart delete(ShoppingCart shoppingCart) {
        //调用查询购物车数据 接口方法 创建对象
        ShoppingCart dbShoppingCart = shoppingCartMapper.findByShoppingCart(shoppingCart);
        //判断购物车是否为空

        if (dbShoppingCart.getNumber()>0){
            dbShoppingCart.setNumber(dbShoppingCart.getNumber()-1);
            //如果购物车有，那就number字段  -1
            shoppingCartMapper.updateNumber(dbShoppingCart.getId(),dbShoppingCart.getNumber());
            if (dbShoppingCart.getNumber()==0){
                shoppingCartMapper.deleteShoppingCart(dbShoppingCart.getId());
                shoppingCartMapper.clean(dbShoppingCart.getId());
            }
        }
        return dbShoppingCart;
    }
}
